package cn.zhz.cloud.token.util;

import cn.zhz.cloud.token.dto.CurrentUserDto;
import com.alibaba.ttl.TransmittableThreadLocal;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ZHZ
 * @date 2022-08-17
 * @apiNote
 */
public class CurrentUserContextHandler {

    private static final TransmittableThreadLocal<Map<String, Object>> CONTEXT = new TransmittableThreadLocal<>();

    private static final String CACHE_KEY_USER = "user";

    private static final String CACHE_KEY_USER_TOKEN = "user_token";

    /**
     * 获取用户信息
     *
     * @return
     */
    public static CurrentUserDto getUser() {
        return (CurrentUserDto) get(CACHE_KEY_USER);
    }

    /**
     * 设置用户信息
     *
     * @return
     */
    public static void setUser(CurrentUserDto currentUserDto) {
        set(CACHE_KEY_USER, currentUserDto);
    }

    /**
     * 设置用户令牌
     *
     * @return
     */
    public static void setUserToken(String userToken) {
        set(CACHE_KEY_USER_TOKEN, userToken);
    }

    /**
     * 获取用户令牌
     *
     * @return
     */
    public static String getUserToken() {
        return (String) get(CACHE_KEY_USER_TOKEN);
    }

    /**
     * 清除
     *
     * @return
     */
    public static void clear() {
        CONTEXT.remove();
    }


    private static void set(String key, Object value) {
        Map<String, Object> map = CONTEXT.get();

        if (map == null) {
            map = new HashMap<>();
            map.put(key, value);
        } else {
            map.put(key, value);
        }
        CONTEXT.set(map);

    }

    private static Object get(String key) {
        Map<String, Object> map = CONTEXT.get();
        return map == null ? null : map.get(key);
    }

}
